package com.three.db.idService;

import com.dangdang.ddframe.rdb.sharding.id.generator.IdGenerator;
import com.dangdang.ddframe.rdb.sharding.id.generator.self.CommonSelfIdGenerator;
import com.three.utils.LogUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * <p>分布式主键生成器,
 * 不同进程的workerID不同
 * 命令参数-Dsjdbc.self.id.generator.worker.id=xxx设置，
 * 如果没有设置，则使用默认的workerId=10000
 * </p>
 */
public class IdService {
    private static final long DEFAULT_WORKER_ID=1023L;
    private static long workerId=0L;
    private static IdGenerator idGenerator;
    static{
        String workerIdStr=System.getProperty("Dsjdbc.self.id.generator.worker.id");
        LogUtils.Console.warn("进程workerId:{}",workerIdStr);
        if(StringUtils.isEmpty(workerIdStr)|| !StringUtils.isNumeric(workerIdStr)){
            workerId=DEFAULT_WORKER_ID;
        }else{
            workerId=Long.valueOf(workerIdStr);
        }
        CommonSelfIdGenerator.setWorkerId(workerId);
        idGenerator=new CommonSelfIdGenerator();
    }

    public static Optional<Long> get(){
        if(Objects.nonNull(idGenerator)){
            return Optional.of(idGenerator.generateId().longValue());
        }
        return Optional.empty();
    }
}
